package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    //静态代码块中向集合中存放所有可以放行的请求或网页地址（不用账号密码即可访问）
    public static ArrayList<String> urls = new ArrayList<>();
    static {
        urls.add("/login.jsp");
        urls.add("/register.jsp");
        urls.add("/LoginServlet");
        urls.add("/RegisterServlet");
        urls.add("/index.jsp");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) req;
        HttpServletResponse servletResponse = (HttpServletResponse) resp;
        HttpSession session = servletRequest.getSession();
        // 获得用户请求的URI
        String path = servletRequest.getRequestURI();
        System.out.println("已进入登陆过滤器，请求地址："+path);
        // 从session里取员工工号信息
        String username = (String) session.getAttribute("username");
        System.out.println("当前Sessiond对象："+username);
        // 登陆页面无需过滤
        for (String url : urls ) {
            if(url.equals(path) || path.contains(url)) {
                //System.out.println("resource do chain...");
                System.out.println("放行！");
                chain.doFilter(req, resp);
                //防止重复响应
                return;
            }
        }
        // 判断如果没有取到员工信息,则未登录，检查是否存在有Cookie信息,若没有就跳转到登陆页面
        if (username == null || "".equals(username)) {
            System.out.println("没有员工信息，开始读取Cookie");
            Cookie[] cookies = servletRequest.getCookies();
            String value = null;//Cookie的值
            if (cookies!=null){
                for (int i=0; i<cookies.length; i++){//获取名称为username的Cookie的值
                    if (cookies[i].getName().equals("user")){
                        value = cookies[i].getValue();
                    }
                    System.out.println("第"+(i+1)+"条Cookie记录："+cookies[i].getName()+"+"+cookies[i].getValue());
                }
            }
            if (value != null){//Cookie值不为空，自动登陆成功
                session.setAttribute("username",value);
                System.out.println("Cookie自动登陆成功！");
                chain.doFilter(req, resp);//放行
                return;
            }else{
                // 跳转到登陆页面
                System.out.println("拦截！");
                servletResponse.sendRedirect("/StuSystem_war_exploded/login.jsp");
            }
        } else {
            // 已经登陆,继续此次请求
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}